const {app} = require("electron");

class PuppeteerWebview {
    page = null

    constructor() {

    }

    async connectWebview (webviewId, cookiesArray) {
        console.log('准备连接webview:', webviewId)
        const browser = app.puppeteer
        const targets = await browser.targets()
        for (const target of targets) {
            if (target.type() === 'webview') {
                // 如果当前目标是 webview 则判断是否是匹配的 webview
                let page = await target.page()
                let webviewIdInPage = await page.evaluate(() => localStorage.getItem("webviewId"))
                if (webviewIdInPage === webviewId) {
                    console.log(`找到了【${webviewId}】对应的webview:`)
                    if (cookiesArray) {
                        await page.setCookie(...cookiesArray)
                    }
                    this.page = page
                }
            }
        }
        return null;
    }

    async goto(url) {
        try {
            await this.page.goto(url)
            console.log(`前往【${url}】页面成功`)
        } catch (e) {
            console.error(`前往【${url}】页面失败`, e)
            throw new Error(`前往【${url}】页面失败`)
        }
    }

    async wait_dom({waitSelector, desc, timeout = 5000}) {
        try {
            let handle = await this.page.waitForSelector(waitSelector, timeout)
            console.log(`【${desc}】成功`)
            return handle
        } catch (e) {
            throw new Error(`【${desc}】失败`)
        }
    }

    async click({handle, desc}){
        try {
            await handle.click()
            console.log(`【${desc}】成功`)
        } catch (e) {
            console.error(`【${desc}】失败：`, e)
            throw new Error(`【${desc}】失败`)
        }
    }

    async click_wait_dom({ handle, waitSelector, desc }) {
        const maxRetries = 5; // 最大重试次数
        const retryInterval = 1000; // 重试间隔时间，单位为毫秒

        for (let retry = 0; retry <= maxRetries; retry++) {
            try {
                await handle.click();
                let waitHandle = await this.page.waitForSelector(waitSelector, { timeout: 1000 });
                console.log(`等待【${waitSelector}】成功`);
                return waitHandle; // 操作成功，退出循环
            } catch (e) {
                if (retry < maxRetries) {
                    console.error(`【${desc}】尝试失败，第 ${retry + 1} 次，将在 ${retryInterval / 1000} 秒后重试：`, e);
                    await new Promise(resolve => setTimeout(resolve, retryInterval));
                } else {
                    console.error(`【${desc}】失败：`, e);
                    throw new Error(`【${desc}】失败，达到最大重试次数`);
                }
            }
        }
    }

    async wait_dom_click({ waitSelector, desc }){
        try {
            let waitHandle = await this.page.waitForSelector(waitSelector, { timeout: 5000 })
            await waitHandle.click()
            console.log(`【${desc}】成功`)
        } catch (e) {
            console.error(`【${desc}】失败：`, e)
            throw new Error(`【${desc}】失败`)
        }
    }


    async write({handle, content, desc}) {
        try {
            await new Promise((resolve) => setTimeout(resolve, 500))
            // await this.page.type(selector, content)
            await handle.type(content)
            console.log(`【${desc}】成功`)
        } catch (e) {
            console.error(`【${desc}】失败`, e)
            throw new Error(`【${desc}】失败`)
        }
    }

    async scrollIntoView(selector){
        await new Promise((resolve) => setTimeout(resolve, 500))
        return this.page.evaluate((selector) => {
            const container = document.querySelector(selector);
            container.scrollIntoView({
                behavior:'smooth'
            });
        }, selector);
    }
}

/**
 * 连接webview
 * @param webviewId
 * @returns {Promise<*|null>}
 */



module.exports = PuppeteerWebview